//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { fetch } from '@tauri-apps/api/http';

export interface GitCodeRepo {
    id: number;
    full_name: string;
    path: string;
    name: string;
    description: string;
    internal: boolean;
    fork: boolean;
    http_url_to_repo: string;
    ssh_url_to_repo: string;
    forks_count: number;
    stargazers_count: number;
    watchers_count: number;
    default_branch: string;
    open_issues_count: number;
    license: string;
    private: boolean;
    public: boolean;
    namespace: {
        name: string;
        path: string;
    };
}

export async function list_user_repo(accessToken: string, userPath: string): Promise<GitCodeRepo[]> {
    const reqUrl = `https://api.gitcode.com/api/v5/users/${encodeURIComponent(userPath)}/repos?access_token=${encodeURIComponent(accessToken)}&per_page=100`;
    const res = await fetch<GitCodeRepo[]>(reqUrl, {
        method: "GET",
        timeout: 10,
    });

    if (res.ok && res.status == 200) {
        return res.data;
    } else {
        console.log(res);
        throw "error list repo";
    }
}

export async function list_org_repo(accessToken: string, orgPath: string): Promise<GitCodeRepo[]> {
    const reqUrl = `https://api.gitcode.com/api/v5/orgs/${encodeURIComponent(orgPath)}/repos?access_token=${encodeURIComponent(accessToken)}&per_page=100`;
    const res = await fetch<GitCodeRepo[]>(reqUrl, {
        method: "GET",
        timeout: 10,
    });

    if (res.ok && res.status == 200) {
        return res.data;
    } else {
        console.log(res);
        throw "error list repo";
    }
}

export async function get_repo(accessToken: string, owerName: string, repoName: string): Promise<GitCodeRepo> {
    const reqUrl = `https://api.gitcode.com/api/v5/repos/${encodeURIComponent(owerName)}/${encodeURIComponent(repoName)}?access_token=${encodeURIComponent(accessToken)}`;
    const res = await fetch<GitCodeRepo>(reqUrl, {
        method: "GET",
        timeout: 10,
    });

    if (res.ok && res.status == 200) {
        return res.data;
    } else {
        console.log(res);
        throw "error list repo";
    }
}